package com.edu.controller;

import com.edu.bean.User;
import com.edu.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {

    @Resource
    public UserService userService;

    @RequestMapping("/register")
    public String register(MultipartFile avatar,
                           @Valid User user,
                           BindingResult bindingResult,
                           Model model,
                           HttpSession session){
        if(bindingResult.hasErrors()){  //判断验证是否出错
            List<FieldError> fieldErrors = bindingResult.getFieldErrors(); //获取 所有的错误信息 List<FieldError>,FieldError代表一条错误性
            Map<String,String> errors = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {  //遍历所有的错误信息
                errors.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            model.addAttribute("errors",errors);
            return "forward:/register.jsp";
        }
        if (userService.userRegister(user)==-1){
            model.addAttribute("msg","用户名已存在请重新取名");
            return "forward:/register.jsp";
        }
        if(avatar != null && !avatar.isEmpty() && avatar.getContentType().contains("image")){
            try {
                String fileName = avatar.getOriginalFilename();//获取文件原始文件名
                String newName = System.currentTimeMillis()+fileName;
                String savePath = "c:/headImgs/"+newName;//确定 文件存储的路径
                String visitPath = "/demo002/headImgs/"+newName;
                avatar.transferTo(new File(savePath));
                userService.updateHeadImg(user.getUsername(),visitPath);
                user.setHeadImg(visitPath);
                session.setAttribute("loginUser",user);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "forward:/success.jsp"; // 注册成功，转发到成功页面
    }

    @RequestMapping("/userLogin")
    public String userLogin(User user, Model model, HttpSession session){
        Map<String, Object> map = userService.userLogin(user);
        if(map.containsKey("loginUser")){
            session.setAttribute("loginUser",map.get("loginUser"));
            return "redirect:/book.jsp";
        }
        model.addAttribute("msg",map.get("msg"));
        return "forward:/login.jsp";
    }
}
